package gui.table;

import gui.App;

import java.sql.SQLException;

import models.DatabaseModel;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Listener;

import databasetranslation.DatabaseList;

/**
 * Class for creating an {@link AutoTable} that stays in sync with a DatabaseList.
 * 
 * It behaves like an AutoTable, but also keeps the DatabaseList 
 * and the rest of the app in sync.
 */
public class AutoTable_DBList < Model extends DatabaseModel, ModelList extends DatabaseList<Model> > {
	
	private AutoTable<Model> table;
	private ModelList list;
	private App app;

	/**
	 * Create a new table, which will be capable of displaying a databaseList.
	 * 
	 * @param parent parent composite
	 * @param tableView {@link TableView} object for mapping the list items to a string representation.  
	 */
	public AutoTable_DBList(App app, Composite parent, TableView<Model> tableView, ListTransformer<Model> transformer) {
		this.table = new AutoTable<Model>(parent, tableView, transformer);
		this.app = app;	
	}
	
	/**
	 * Set the list to be displayed. (GUI will be updated.)
	 * @param list
	 */
	public void setList(ModelList list) {
		this.list = list;
		update();
		table.pack();
	}
	
	/**
	 * Adds an entry to the list and updates the table displayed.
	 * @param entry
	 * @throws SQLException
	 */
	public void add(Model entry) throws SQLException {
		list.add(entry);
		app.updateAll();
	}
	
	/**
	 * Replaces the data of an entry with new values, and updates the table displayed.
	 * @param entry Entry to update, with new data
	 * @throws SQLException
	 */
	public void replace(Model entry) throws SQLException {
		list.replace(entry);
		app.updateAll();
	}
	
	/**
	 * Deletes an entry, and updates the table displayed.
	 * @param entry
	 * @throws SQLException
	 */
	public void delete(Model entry) throws SQLException {
		list.delete(entry);
		app.updateAll();
	}
	
	/**
	 * Update the AutoTable with the current contents of the DatabaseList.
	 */
	public void update() {
		table.setList(list.getEntries());
		table.update();
	}

	/** Delegates call to Autotable */
	public void setLayoutData(Object layoutData) {
		table.setLayoutData(layoutData);
	}
	
	/** Delegates call to Autotable */
	public void addListener(int eventType, Listener listener) {
		table.addListener(eventType, listener);
	}

	/** Delegates call to Autotable */
	public Model getSelected() {
		return table.getSelected();
	}

}
